<template>
  <div class="main_box">
    <el-row class="header-row">
      <el-col>
        <div class="search_wrap">
          <el-form :inline="true" :model="filters" class="demo-form-inline" ref="searchForm">
            <el-form-item prop="activeNo">
              <el-input v-model="filters.activeNo" clearable placeholder="请输入活动编号"></el-input>
            </el-form-item>
            <el-form-item prop="activeName">
              <el-input v-model="filters.activeName" clearable placeholder="请输入活动名称"></el-input>
            </el-form-item>
            <el-form-item prop="activeType">
              <el-select v-model="filters.activeType" clearable placeholder="请选择活动类型">
                <el-option :value="1" label="店铺活动" :key="1"> </el-option>
                <el-option :value="2" label="缴费活动" :key="2"> </el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="businessId">
              <el-select v-model="filters.businessId" clearable filterable placeholder="请选择商户"> <el-option v-for="item in businessList" :value="item.id" :label="item.name" :key="item.id"> </el-option>> </el-select>
            </el-form-item>
            <el-form-item>
              <el-button icon="el-icon-search" type="primary" @click="onSearch">查询</el-button>
              <el-button icon="el-icon-refresh-left" @click="resetForm">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-col>
      <el-col>
        <div class="opration_wrap">
          <el-tooltip content="刷新" placement="top">
            <el-button circle icon="el-icon-refresh-right" @click="reload" size="mini"></el-button>
          </el-tooltip>
          <div>
            <el-button type="primary" plain icon="fa fa-plus" v-has="permissionAdd" @click="handleClickAdd()" size="mini"> 新增</el-button>
          </div>
        </div>
      </el-col>
    </el-row>

    <el-row ref="tableRow">
      <!-- 列表 -->
      <el-table ref="tableList" :data="dataList" :fit="true" highlight-current-row v-loading="listLoading" element-loading-text="数据加载中，请稍后..." empty-text="对不起，没有找到相关数据！">
        <el-table-column type="index" label="序号" width="50" align="center"></el-table-column>
        <el-table-column align="center" label="活动编号" prop="activeNo"> </el-table-column>
        <el-table-column align="center" label="活动名称" prop="activeName"> </el-table-column>
        <el-table-column align="center" label="商家" prop="businessName"> </el-table-column>
        <el-table-column align="center" label="活动类型">
          <template slot-scope="scope">
            {{ scope.row.activeType == 1 ? '店铺活动' : '缴费活动' }}
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" width="100">
          <template slot-scope="scope">
            <span>
              <el-tag size="mini" effect="dark" :type="formatStates(scope.row.state)">
                {{ formatState(scope.row.state) }}
              </el-tag>
            </span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="创建时间" prop="createDate"> </el-table-column>
        <el-table-column label="操作" width="256" align="center" fixed="right">
          <template slot-scope="scope">
            <el-button v-has="permissionCheck" @click="handleClickDetail(scope.row)" size="mini">查看</el-button>
            <el-button v-has="permissionBusinessVillage" @click="handleAddAV(scope.row)" size="mini">设置经营范围</el-button>
            <el-dropdown trigger="click" size="small">
              <el-button type="primary"> <i class="fa fa-list-ul"></i>更多 </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item v-has="permissionEdit" @click.native="handleClickEditor(scope.row)">编辑 </el-dropdown-item>
                <el-dropdown-item v-has="permissionUpStatus" @click.native="handleIsDisable(scope.row)"> {{ scope.row.state === 0 ? '启用' : '禁用' }}</el-dropdown-item>
                <el-dropdown-item v-has="permissionDelete" @click.native="handleClickDelete(scope.row)">删除</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页工具条 -->
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page.pageNo"
        :page-sizes="[20, 50, 100]"
        :page-size="page.pageSize"
        layout="total, sizes, jumper, next, pager, prev"
        :total="page.pageTotal"
      ></el-pagination>

      <ActiveVillage v-model="activeVillage.show" :list="activeVillage.list" @confirm="handleConfirmAV"></ActiveVillage>
    </el-row>
  </div>
</template>
<script>
import * as message from '@/constants/message';
import ActiveApi from '@/api/operation/active';
import BusinessApi from '@/api/business/business';
import ActiveVillage from './components/ActiveVillage.vue';
export default {
  name: 'ActiveManagement',
  inject: ['reload'], //注入局部刷新
  data() {
    return {
      listLoading: true,
      filters: {
        activeNo: '',
        activeName: '',
        activeType: '',
        businessId: '',
      },
      dataList: [],
      businessList: [],
      page: {
        pageNo: 1,
        pageTotal: 0,
        pageSize: 20,
      },

      permissionCheck: 'SYSTEM_MANAGER_OPERATION_ACTIVE_LIST_SEE',
      permissionAdd: 'SYSTEM_MANAGER_OPERATION_ACTIVE_LIST_ADD',
      permissionEdit: 'SYSTEM_MANAGER_OPERATION_ACTIVE_LIST_EDIT',
      permissionUpStatus: 'SYSTEM_MANAGER_OPERATION_ACTIVE_LIST_STATE',
      permissionDelete: 'SYSTEM_MANAGER_OPERATION_ACTIVE_LIST_DELETE',
      permissionBusinessVillage: 'SYSTEM_MANAGER_OPERATION_ACTIVE_LIST_BUSINESS_SERVER',
      activeVillage: {
        show: false,
        list: [],
      },
      rowItem: {},
    };
  },
  mounted() {
    this.init();
    window.addEventListener('keydown', this.keyDown);
  },
  activated() {
    this.listData();
  },
  destroyed() {
    window.removeEventListener('keydown', this.keyDown, false);
  },
  components: {
    ActiveVillage,
  },
  watch: {},
  methods: {
    init() {
      this.listLoading = true;
      this.listData();
      this.getBusinessList();
      this.getTableHeight();
    },
    keyDown(e) {
      //如果是回车则执行查询方法
      if (e.keyCode == 13) {
        this.onSearch();
      }
    },
    getTableHeight() {
      this.$nextTick(function () {
        this.maxHeight = window.innerHeight - this.$refs.tableRow.$el.offsetTop - 50;
        window.onresize = () => {
          this.maxHeight = window.innerHeight - this.$refs.tableRow.$el.offsetTop - 50;
        };
      });
    },
    // 获取商户列表
    getBusinessList() {
      BusinessApi.listIdNameVo().then((res) => {
        this.businessList = res.data;
      });
    },
    handleAddAV(row) {
      const { businessId, activeId } = (this.rowItem = row);
      const { activeVillage } = this;
      activeVillage.list = [];
      const params = {
        businessId,
        activeId,
      };
      ActiveApi.getMapData(params).then((res) => {
        const { data } = res;
        Object.keys(data).forEach((item) => {
          const obj = {};
          if (item == 1) obj.name = '专属';
          if (item == 2) obj.name = '小区';
          if (item == 3) obj.name = '公里数';
          if (item == 4) obj.name = '地区';
          obj.list = data[item];
          obj.ids = data[item].filter((item2) => item2.state).map((item2) => item2.businessVillageId);
          activeVillage.list.push(obj);
        });
        activeVillage.show = true;
      });
    },
    handleConfirmAV() {
      const { activeVillage, rowItem } = this;
      let ids = [];
      activeVillage.list.forEach((item) => {
        ids = ids.concat(item.ids);
      });
      const params = {
        id: rowItem.activeId,
        ids,
      };
      ActiveApi.setActiveVillage(params).then(() => {
        this.$Utils.notifySuccess('设置成功');
        activeVillage.show = false;
      });
    },
    handleSizeChange(size) {
      this.page.pageSize = size;
      this.listData();
    },
    handleCurrentChange(val) {
      this.page.pageNo = val;
      this.listData();
    },
    handleIsDisable(row) {
      let currentState = row.state === 0 ? 1 : 0;
      this.$confirm(currentState ? '是否启用？' : '是否禁用', message.TITLE_PROMPT, {}).then(() => {
        ActiveApi.deleteActive({
          id: row.activeId,
          state: currentState,
        }).then((res) => {
          this.$Utils.notifySuccess();
          this.listData();
        });
      });
    },
    handleClickDelete(val) {
      // 删除
      this.$confirm('是否删除该活动', message.TITLE_PROMPT, {}).then(() => {
        var cond = {
          id: val.activeId,
          state: -1,
        };
        ActiveApi.deleteActive(cond).then((data) => {
          this.$Utils.notifySuccess();
          this.listData();
        });
      });
    },
    handleClickEditor(val) {
      //编辑 进入新增页通过id来查找数据
      let _this = this;
      _this.$router.push({
        path: '/operation/activeEdit',
        query: { id: val.activeId },
      });
    },
    handleClickAdd() {
      this.$router.push('/operation/activeAdd');
    },
    handleClickDetail(row) {
      this.$router.push({
        path: '/operation/activeDetail',
        query: { id: row.activeId },
      });
    },
    formatState(cellValue) {
      if (cellValue === -1) {
        return '删除';
      } else if (cellValue === 0) {
        return '禁用';
      } else if (cellValue === 1) {
        return '启用';
      }
    },
    formatStates(cellValue) {
      if (cellValue === -1) {
        return 'danger';
      } else if (cellValue === 0) {
        return 'info';
      } else if (cellValue === 1) {
        return 'success';
      }
    },
    resetForm() {
      this.$refs.searchForm.resetFields();
      this.onSearch();
    },
    onSearch() {
      this.page.pageNo = 1;
      this.listData();
    },
    listData() {
      // 获取列表数据
      let cond = {
        pageNo: this.page.pageNo,
        pageSize: this.page.pageSize,
        activeName: this.filters.activeName,
        activeType: this.filters.activeType,
        activeNo: this.filters.activeNo,
        businessId: this.filters.businessId,
        // ruleType:_this.filters.ruleType,
      };

      this.listLoading = true;
      ActiveApi.listActive(cond)
        .then((res) => {
          this.dataList = res.data.list;
          this.page.pageTotal = res.data.total;
        })
        .finally(() => {
          this.$refs.tableList.doLayout();
          this.listLoading = false;
        });
    },
  },
};
</script>
<style lang="scss">
@import '@/assets/css/views/content.scss';
</style>
